<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="800px"
    :before-close="handleClose"
    class="unified-dialog task-config-dialog"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon" :class="headerIconClass">
          <el-icon><component :is="headerIcon" /></el-icon>
        </div>
        <div class="header-content">
          <h3>{{ dialogTitle }}</h3>
          <p>{{ dialogDescription }}</p>
        </div>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="140px"
      label-position="left"
      class="task-config-form"
    >
      <!-- 基础信息 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Document /></el-icon>
          <span>基础信息</span>
        </div>

        <el-form-item label="环境" prop="env_id">
          <el-select
            v-model="form.env_id"
            placeholder="选择环境"
            :disabled="isViewMode || isEditMode"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          >
            <el-option
              v-for="env in envList"
              :key="env.id"
              :label="env.env_name"
              :value="env.id"
            />
          </el-select>
          <span class="form-tip" v-if="!isViewMode && isEditMode">环境创建后不可修改</span>
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-input
            v-model="form.category"
            placeholder="请输入分类"
            :disabled="isViewMode"
            clearable
          />
        </el-form-item>

        <el-form-item label="Key前缀" prop="key_prefix">
          <el-input
            v-model="form.key_prefix"
            placeholder="请输入Redis key前缀"
            :disabled="isViewMode || isEditMode"
            clearable
          />
          <span class="form-tip" v-if="!isViewMode && isEditMode">Key前缀创建后不可修改</span>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息（可选）"
            :disabled="isViewMode"
            clearable
          />
        </el-form-item>
      </div>

      <!-- 监控设置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><View /></el-icon>
          <span>监控设置</span>
        </div>

        <el-form-item label="启用监控" prop="is_monitored">
          <div class="switch-container">
            <el-switch
              v-model="form.is_monitored"
              :active-value="1"
              :inactive-value="0"
              :disabled="isViewMode"
              size="large"
            />
            <div class="switch-description">
              <p class="description-title">监控数据收集</p>
              <p class="description-text">启用后将定时扫描Redis key并收集任务数据</p>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="扫描数量" prop="scan_count">
          <el-input-number
            v-model="form.scan_count"
            :min="100"
            :max="10000"
            :step="100"
            :disabled="isViewMode"
            controls-position="right"
            style="width: 100%"
          />
          <span class="form-tip">每次SCAN扫描的key数量，推荐500</span>
        </el-form-item>

        <el-form-item label="采样大小" prop="sample_size">
          <el-input-number
            v-model="form.sample_size"
            :min="100"
            :max="10000"
            :step="100"
            :disabled="isViewMode"
            controls-position="right"
            style="width: 100%"
          />
          <span class="form-tip">每个前缀最多保存的数据条数，推荐1000</span>
        </el-form-item>
      </div>

      <!-- 任务类型过滤 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Filter /></el-icon>
          <span>任务类型过滤</span>
        </div>

        <el-form-item label="过滤模式" prop="task_type_mode">
          <el-radio-group v-model="form.task_type_mode" :disabled="isViewMode">
            <el-radio label="all">全部类型</el-radio>
            <el-radio label="include">仅包含</el-radio>
            <el-radio label="exclude">排除</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="form.task_type_mode !== 'all'"
          label="任务类型"
          prop="task_type_filter"
        >
          <el-input
            v-model="form.task_type_filter"
            placeholder="请输入任务类型，逗号分隔（如：4,5,6）"
            :disabled="isViewMode"
            clearable
          />
          <span class="form-tip">多个任务类型用逗号分隔</span>
        </el-form-item>
      </div>

      <!-- 告警设置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Bell /></el-icon>
          <span>告警设置</span>
        </div>

        <el-form-item label="启用告警" prop="is_alert_enabled">
          <div class="switch-container">
            <el-switch
              v-model="form.is_alert_enabled"
              :active-value="1"
              :inactive-value="0"
              :disabled="isViewMode"
              size="large"
            />
            <div class="switch-description">
              <p class="description-title">告警通知</p>
              <p class="description-text">启用后当触发告警条件时会发送通知</p>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="Webhook地址" prop="webhook_url">
          <el-input
            v-model="form.webhook_url"
            placeholder="企业微信/钉钉Webhook地址（可选）"
            :disabled="isViewMode"
            clearable
          />
          <span class="form-tip">留空则使用系统默认配置</span>
        </el-form-item>

        <el-form-item label="提前删除告警" prop="alert_on_early_delete">
          <el-radio-group v-model="form.alert_on_early_delete" :disabled="isViewMode">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
          <span class="form-tip">键被提前删除时是否告警</span>
        </el-form-item>

        <el-form-item label="过期告警" prop="alert_on_expire">
          <el-radio-group v-model="form.alert_on_expire" :disabled="isViewMode">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
          <span class="form-tip">键正常过期时是否告警</span>
        </el-form-item>
      </div>

      <!-- 状态设置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Setting /></el-icon>
          <span>状态设置</span>
        </div>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" :disabled="isViewMode">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="paused">暂停</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!-- 只读信息（查看模式） -->
      <div v-if="isViewMode && taskConfig" class="form-section">
        <div class="section-title">
          <el-icon><InfoFilled /></el-icon>
          <span>运行状态</span>
        </div>

        <el-form-item label="告警状态">
          <el-tag :type="taskConfig.alert_status === 'alerting' ? 'danger' : 'success'" size="small">
            {{ taskConfig.alert_status === 'alerting' ? '告警中' : '正常' }}
          </el-tag>
        </el-form-item>

        <el-form-item label="最后扫描时间">
          <el-input :model-value="taskConfig.last_scan_time || '-'" disabled />
        </el-form-item>

        <el-form-item label="最新key数量">
          <el-input :model-value="taskConfig.latest_key_count || 0" disabled />
        </el-form-item>

        <el-form-item label="最后告警时间">
          <el-input :model-value="taskConfig.last_alert_time || '-'" disabled />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-input :model-value="taskConfig.created_at || '-'" disabled />
        </el-form-item>

        <el-form-item label="更新时间">
          <el-input :model-value="taskConfig.updated_at || '-'" disabled />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="!isViewMode"
          type="primary"
          @click="handleSubmit"
          :loading="loading"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  View, Edit, Plus, Document, InfoFilled, Bell, Setting, Filter
} from '@element-plus/icons-vue'
import { useRedisTaskMonitorStore } from '@/stores/redisTaskMonitor'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('TaskConfigDialog')
const store = useRedisTaskMonitorStore()

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  taskConfig: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'create'
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isViewMode = computed(() => props.mode === 'view')
const isEditMode = computed(() => props.mode === 'edit')
const isCreateMode = computed(() => props.mode === 'create')

const dialogTitle = computed(() => {
  if (isViewMode.value) return '查看任务配置'
  if (isEditMode.value) return '编辑任务配置'
  return '新建任务配置'
})

const dialogDescription = computed(() => {
  if (isViewMode.value) return '查看任务监控配置详细信息'
  if (isEditMode.value) return '修改任务监控配置信息'
  return '创建新的任务监控配置'
})

const headerIcon = computed(() => {
  if (isViewMode.value) return View
  if (isEditMode.value) return Edit
  return Plus
})

const headerIconClass = computed(() => {
  if (isViewMode.value) return 'header-icon-primary'
  if (isEditMode.value) return 'header-icon-warning'
  return 'header-icon-success'
})

const envList = computed(() => store.envConfigsList)

const formRef = ref(null)
const loading = ref(false)

const form = reactive({
  env_id: null,
  category: '',
  key_prefix: '',
  description: '',
  is_monitored: 1,
  is_alert_enabled: 0,
  scan_count: 500,
  sample_size: 1000,
  task_type_filter: '',
  task_type_mode: 'all',
  webhook_url: '',
  alert_on_early_delete: 1,
  alert_on_expire: 0,
  status: 'active'
})

const rules = {
  env_id: [
    { required: true, message: '请选择环境', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请输入分类', trigger: 'blur' }
  ],
  key_prefix: [
    { required: true, message: '请输入Key前缀', trigger: 'blur' }
  ],
  scan_count: [
    { required: true, message: '请输入扫描数量', trigger: 'blur' },
    { type: 'number', min: 100, max: 10000, message: '扫描数量范围：100-10000', trigger: 'blur' }
  ],
  sample_size: [
    { required: true, message: '请输入采样大小', trigger: 'blur' },
    { type: 'number', min: 100, max: 10000, message: '采样大小范围：100-10000', trigger: 'blur' }
  ]
}

// 监听taskConfig变化，填充表单
watch(() => props.taskConfig, (newVal) => {
  if (newVal) {
    Object.assign(form, {
      env_id: newVal.env_id || null,
      category: newVal.category || '',
      key_prefix: newVal.key_prefix || '',
      description: newVal.description || '',
      is_monitored: newVal.is_monitored !== undefined ? newVal.is_monitored : 1,
      is_alert_enabled: newVal.is_alert_enabled !== undefined ? newVal.is_alert_enabled : 0,
      scan_count: newVal.scan_count || 500,
      sample_size: newVal.sample_size || 1000,
      task_type_filter: newVal.task_type_filter || '',
      task_type_mode: newVal.task_type_mode || 'all',
      webhook_url: newVal.webhook_url || '',
      alert_on_early_delete: newVal.alert_on_early_delete !== undefined ? newVal.alert_on_early_delete : 1,
      alert_on_expire: newVal.alert_on_expire !== undefined ? newVal.alert_on_expire : 0,
      status: newVal.status || 'active'
    })
  } else {
    // 重置表单
    Object.assign(form, {
      env_id: null,
      category: '',
      key_prefix: '',
      description: '',
      is_monitored: 1,
      is_alert_enabled: 0,
      scan_count: 500,
      sample_size: 1000,
      task_type_filter: '',
      task_type_mode: 'all',
      webhook_url: '',
      alert_on_early_delete: 1,
      alert_on_expire: 0,
      status: 'active'
    })
  }
}, { immediate: true, deep: true })

// 监听对话框显示状态，加载环境列表
watch(visible, (val) => {
  if (val) {
    store.fetchEnvConfigsList()
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  }
})

const handleClose = () => {
  visible.value = false
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    loading.value = true

    const formData = {
      env_id: form.env_id,
      category: form.category,
      key_prefix: form.key_prefix,
      description: form.description,
      is_monitored: form.is_monitored,
      is_alert_enabled: form.is_alert_enabled,
      scan_count: form.scan_count,
      sample_size: form.sample_size,
      task_type_mode: form.task_type_mode,
      webhook_url: form.webhook_url,
      alert_on_early_delete: form.alert_on_early_delete,
      alert_on_expire: form.alert_on_expire,
      status: form.status
    }

    // 只有在非all模式时才包含task_type_filter
    if (form.task_type_mode !== 'all' && form.task_type_filter) {
      formData.task_type_filter = form.task_type_filter
    }

    if (isCreateMode.value) {
      await store.createTaskConfig(formData)
    } else if (isEditMode.value) {
      await store.updateTaskConfig(props.taskConfig.id, formData)
    }

    ElMessage.success(isCreateMode.value ? '创建成功' : '更新成功')
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== false) {
      // 验证失败时不显示错误消息
      componentLogger.error('提交失败', error)
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.task-config-dialog :deep(.el-dialog__header) {
  padding: 0;
}

.task-config-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.header-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.header-icon-primary {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.header-icon-warning {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

.header-icon-success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.header-content h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-content p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.task-config-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 8px;
  border-bottom: 2px solid #ebeef5;
}

.switch-container {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.switch-description {
  flex: 1;
}

.description-title {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.description-text {
  margin: 0;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.form-tip {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>
